package com.example.library.widget.textview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Shader;
import android.text.TextPaint;
import android.util.AttributeSet;

import com.example.library.R;

import androidx.appcompat.widget.AppCompatTextView;

/**
 * 不能动态设置文字设置颜色
 * Description: 闪烁文字——color,red translate red  @line 44
 */
public class FlashTextView extends AppCompatTextView {

    private int mViewWidth;
    private TextPaint mPaint;
    private LinearGradient mLinearGradient;
    private Matrix mGradientMatrix;
    private int mTranslate;
    private int[] mColors = new int[]{};

    public FlashTextView(Context context) {
        this(context, null);
    }

    public FlashTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FlashTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mColors = context.getResources().getIntArray(R.array.rainbow);
    }

    private void setGradientColor(int[] colors) {
        if (colors == null || colors.length <= 1) {
            mLinearGradient = new LinearGradient(0, 0, mViewWidth, 0, mColors, null, Shader.TileMode.CLAMP);
            return;
        }
        mLinearGradient = new LinearGradient(0, 0, mViewWidth, 0, colors, null, Shader.TileMode.CLAMP);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (mViewWidth == 0) {
            mViewWidth = getMeasuredWidth();
            if (mViewWidth > 0) {
                mPaint = getPaint();
                setGradientColor(mColors);
                mPaint.setShader(mLinearGradient);
                mGradientMatrix = new Matrix();
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mGradientMatrix != null) {
            mTranslate += mViewWidth / 5;
            if (mTranslate > 2 * mViewWidth) {
                mTranslate = -mViewWidth;
            }
            mGradientMatrix.setTranslate(mTranslate, 0);
            mLinearGradient.setLocalMatrix(mGradientMatrix);
            postInvalidateDelayed(100);
        }
    }
}
